<?php
namespace App\Models;

use Illuminate\Support\Facades\DB;
use App\MessageModel;
use App\AdModel;
use App\UserModel;

class Message 
{
    
    //测试模型
    public function messageAll()
    {
        $ad = AdModel::where('ctxtype',0)
        ->hasOneMessage()
        ->get();
        
        return $ad;
    }
    
    /**
     * 留言列表
     * 
     * @author 谢望鑫 <xiewxin@addcn.com>
     * @param $param['direction'] 手势
     * @param $param['from'] 锚点
     * @param $param['fetch'] 每页取几条，默认10
     * @param $param['ctxtype'] 内容类型；-1-全部，0-留言
     * 
     * $return $messageData
     */
    public function messageList($param)
    {
        $direction = !empty($param['direction']) ? (int)$param['direction'] : 1;//手势行为
        $from = !empty($param['from']) ? (int)$param['from'] : 0;//游标
        $fetch = !empty($param['fetch']) ? (int)$param['fetch'] : 10;//每次请求记录数
        $ctxtype = isset($param['ctxtype']) ? (int)$param['ctxtype'] : '';//内容类型；''-全部，0-文章，1-动态（可加图片九张或视频一个），2-交易信息，3-评论，4-留言，5-回复，6-分享
        $query_count = 0;
        $total_count = 0;
        $sub_where = array();
        $sub_where2 = array();
        
        if ($direction == 1) {//下拉刷新,请求最新
            $sub_where[] = ['ad.id', '>', $from];
        } else if($direction == 2) {//上拉刷新,往下加载
            $sub_where[] = ['ad.id', '<', $from];
        } else if($direction == 3) {//用于局部刷新
            $sub_where[] = ['ad.id', '=', $from];
        }
        
        $sub_where2[] = ['ad.status', '=', 1];
        //分类筛选
        if ($ctxtype !== '') {
            $sub_where2[] = ['ad.ctxtype', '=', $ctxtype];
        }
        
        $messageData = AdModel::select('ad.id',
            'ad.usertype',
            'ad.userid',
            'ad.ctxtype',
            'ad.ctxid',
            'ad.more',
            'ad.status',
            'ad.createtime',
            'user.nickname',
            'user.phone',
            'user.avatar',
            'ad_message.title',
            'ad_message.pic1',
            'ad_message.pic2',
            'ad_message.pic3',
            'ad_message.pic4',
            'ad_message.pic5',
            'ad_message.pic6',
            'ad_message.pic7',
            'ad_message.pic8',
            'ad_message.pic9'
            )
            ->leftjoin('user', 'ad.userid', '=', 'user.id')
            ->leftjoin('ad_message', 'ad.ctxid', '=', 'ad_message.id')
            ->where($sub_where2)
            ->where($sub_where)
            ->orderBy('ad.createtime', 'desc')
            ->limit($fetch)
            ->get();
        
            $query_count = count($messageData);
            
            $total_count = AdModel::where($sub_where2)
            ->count();
         
         return array('res' => $messageData, 'total_count' => $total_count, 'query_count' => $query_count);
    }
    /**
     * 留言
     * @author 谢望鑫 <xiewxin@addcn.com>
     * @param $param['usertype'] 用户类型，0-普通用户，1-管理员
     * @param $param['userid'] 用户id
     * @param $param['title'] 留言内容
     * $return $messageData
     */
    public function sendMsg($param)
    {   
        $messageModel = new MessageModel();
        $newtime = time();
        $ctxid = 0;
        $adid = 0;
        $status = 201;
        
        //message数据
        $data['usertype'] = $param['usertype'];
        $data['userid'] = $param['userid'];
        $data['title'] = urlencode($this->remove_xss($param['title']));
        $data['pic1'] = urlencode($this->remove_xss($param['pic1']));
        $data['pic2'] = urlencode($this->remove_xss($param['pic2']));
        $data['pic3'] = urlencode($this->remove_xss($param['pic3']));
        $data['pic4'] = urlencode($this->remove_xss($param['pic4']));
        $data['pic5'] = urlencode($this->remove_xss($param['pic5']));
        $data['pic6'] = urlencode($this->remove_xss($param['pic6']));
        $data['pic7'] = urlencode($this->remove_xss($param['pic7']));
        $data['pic8'] = urlencode($this->remove_xss($param['pic8']));
        $data['pic9'] = urlencode($this->remove_xss($param['pic9']));
        $data['createtime'] = $newtime;
        $data['status'] = 1;
       
        //ad数据
        $adData['usertype'] = $param['usertype'];
        $adData['userid'] = $param['userid'];
        $adData['ctxtype'] = 0;
        $adData['createtime'] = $newtime;
        $adData['status'] = 1;
        
        DB::transaction(function () use($data, $adData, &$ctxid, &$adid) {
            $ctxid=MessageModel::insertGetId($data);
            $adData['ctxid'] = $ctxid;
            $adid = AdModel::insertGetId($adData);
        });
   
        if ($ctxid && $adid) {
            UserModel::where('id',$adData['userid'])->increment('messagecount');
            $status = 200;
        }
        
        return array('code' => $status, 'adid' => $adid, 'ctxtype' => 0, 'ctxid' => $ctxid);
    }
    
    /**
     * 防xss注入
     * @author 谢望鑫 <xiewxin@addcn.com>
     * @param $val 需要过滤的内容
     * $return $val
     */
    public function remove_xss($val) {
        // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
        // this prevents some character re-spacing such as <java\0script>
        // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
        $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
        
        // straight replacements, the user should never need these since they're normal characters
        // this prevents like <IMG SRC=@avascript:alert('XSS')>
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|\'\\';
        for ($i = 0; $i < strlen($search); $i++) {
            // ;? matches the ;, which is optional
            // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
            
            // @ @ search for the hex values
            $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
            // @ @ 0{0,7} matches '0' zero to seven times
            $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
        }
        
        // now the only remaining whitespace attacks are \t, \n, and \r
        $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'base');
        $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
        $ra = array_merge($ra1, $ra2);
        
        $found = true; // keep replacing as long as the previous round replaced something
        while ($found == true) {
            $val_before = $val;
            for ($i = 0; $i < sizeof($ra); $i++) {
                $pattern = '/';
                for ($j = 0; $j < strlen($ra[$i]); $j++) {
                    if ($j > 0) {
                        $pattern .= '(';
                        $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                        $pattern .= '|';
                        $pattern .= '|(&#0{0,8}([9|10|13]);)';
                        $pattern .= ')*';
                    }
                    $pattern .= $ra[$i][$j];
                }
                $pattern .= '/i';
                $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
                $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
                if ($val_before == $val) {
                    // no replacements were made, so exit the loop
                    $found = false;
                }
            }
        }
        return $val;
    }
    
    
}